import java.util.Arrays;
import java.util.Random;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:
 * Date: 2025-10-29
 * Time: 21:15
 */
class Solution{
    public int[] smallestK(int[] nums, int k){
        qsort(nums, 0, nums.length - 1, k);

        int[] ret = new int[k];
        for(int i = 0; i < k; i++){
            ret[i] = nums[i];
        }
        return ret;
    }

    public void qsort(int[] nums, int l, int r, int k){
        if(l > r) return;

        int key = nums[new Random().nextInt(r - l + 1) + l];

        int left = l - 1, right = r + 1, i = l;
        while(i < right){
            if(nums[i] < key) swap(nums, ++left, i++);
            else if(nums[i] == key) i++;
            else swap(nums, --right, i);
        }

        int a = left - l + 1, b = right - left - 1;
        if(k < a) qsort(nums, l, left, k);
        else if(k <= a + b) return;
        else qsort(nums, right, r, k - a - b);
    }

    public void swap(int[] nums, int j ,int k){
        int t = nums[j];
        nums[j] = nums[k];
        nums[k] = t;
    }
}



public class demo1 {
    public static void main(String[] args) {
        int[] nums = {1,3,5,6,8,9,25};
        Solution solution = new Solution();
        int[] ret = solution.smallestK(nums, 5);
        System.out.println(Arrays.toString(ret));
    }
}
